using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(LchTextureArraySettings))]
public class LchTextureArraySettingsEditor : Editor
{
    Texture2D bump;
    void createTexture(List<Texture2D> textures,int Length, string savePath,bool isNormal)
    {
        int count =  Length;
        var tex = textures[0];
        int width = tex.width;
        int height = tex.height;

 
        Texture2D finals = new Texture2D(width* count, height, TextureFormat.RGBA32, true);
        RenderTexture rt0 =   RenderTexture.GetTemporary(width,height,0,RenderTextureFormat.ARGB32);
        for (int i = 0; i <  Length; i++)
        {
            Graphics.Blit(textures[i], rt0);
            RenderTexture.active = rt0;
            finals.ReadPixels(new Rect(0, 0, width, height), i* width, 0);
        }
        finals.Apply();
      

        string pngPath = savePath   + ".png";


        System.IO.File.WriteAllBytes(pngPath, finals .EncodeToPNG());
        AssetDatabase.ImportAsset(pngPath);
        GameObject.DestroyImmediate(finals);
        RenderTexture.ReleaseTemporary(rt0);
        string metaPath = pngPath+ ".meta";

        string [] lines = System.IO.File.ReadAllLines(metaPath);

        for (int i = 0; i < lines.Length; i++)
        {
            string txt = lines[i];
            if (txt.Contains("textureShape"))
            {
                lines[i] = "  textureShape: 4";
            }
            else if (txt.Contains("flipbookColumns"))
            {
                lines[i] = "  flipbookColumns: " + count;
            }
            else if (isNormal)
            {
                if (txt.Contains("sRGBTexture"))
                {
                    lines[i] = "  sRGBTexture: 0"  ;
                }
                else if (txt.Contains("textureType"))
                {
                    lines[i] = "  textureType: 1";
                }
            }
            
        }
        System.IO.File.WriteAllLines(metaPath, lines);
        AssetDatabase.ImportAsset(pngPath);
        AssetDatabase.Refresh();
    }
 
    void createTexturePBR(List<Texture2D> normals, List<Texture2D> channels, int Length, string savePath )
    {
 
        int count = Length;
        var tex = normals[0];
        int width = tex.width;
        int height = tex.height;


        Texture2D finals = new Texture2D(width * count, height, TextureFormat.RGBA32, true);
        Texture2D finals2 = new Texture2D(width * count, height, TextureFormat.RGBA32, true);
        RenderTexture rt0 = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.ARGB32);
        for (int i = 0; i < Length; i++)
        {
            Graphics.Blit(channels[i], rt0);
            RenderTexture.active = rt0;
            finals.ReadPixels(new Rect(0, 0, width, height), i * width, 0);
        }
        finals.Apply();


        for (int i = 0; i < Length; i++)
        {
            Graphics.Blit(normals[i], rt0);
            RenderTexture.active = rt0;
            finals2.ReadPixels(new Rect(0, 0, width, height), i * width, 0);
        }
        finals2.Apply();

        for (int i = 0; i < finals.width; i++)
        {
            for (int j = 0; j < finals2.height; j++)
            {
                var col0 = finals.GetPixel(i, j);
                var col1 = finals2.GetPixel(i, j);
                col0.g = Mathf.GammaToLinearSpace( col1.r);
                col0.b = Mathf.GammaToLinearSpace(col1.g);

                finals.SetPixel(i, j, col0);
            }
        }

        //合并通道

        string pngPath = savePath + ".png";


        System.IO.File.WriteAllBytes(pngPath, finals.EncodeToPNG());
        AssetDatabase.ImportAsset(pngPath);
        GameObject.DestroyImmediate(finals);
        GameObject.DestroyImmediate(finals2);
        
        GameObject.DestroyImmediate(rt0);
        string metaPath = pngPath + ".meta";

        string[] lines = System.IO.File.ReadAllLines(metaPath);

        for (int i = 0; i < lines.Length; i++)
        {
            string txt = lines[i];
            if (txt.Contains("textureShape"))
            {
                lines[i] = "  textureShape: 4";
            }
            else if (txt.Contains("flipbookColumns"))
            {
                lines[i] = "  flipbookColumns: " + count;
            }
            if (txt.Contains("sRGBTexture"))
            {
                lines[i] = "    sRGBTexture: 0";
            }
            /*else if (txt.Contains("textureType"))
            {
                lines[i] = "  textureType: 1";
            }*/

        }
        System.IO.File.WriteAllLines(metaPath, lines);
        AssetDatabase.ImportAsset(pngPath);
    }
    void extendArray(List<Texture2D> ary ,int count)
    {
        while (ary.Count < count)
        {
            ary.Add(null);
        }
    }
    void checkSameSize(List<Texture2D> textures, int textureCount, ref string errorTex)
    {
        // 如果图片尺寸不一致，则提示错误
        if (textureCount > 0)
        {

            for (int i = 0; i < textureCount; i++)
            {
                if (null == textures[i])
                {
                    errorTex +="第"+i+"存在空贴图";
                    break;
                }
                
                if (i>0 && (textures[i].width != textures[0].width || textures[i].height != textures[0].height ))
                {
                    errorTex +=   "第" + i + "大小不一致";
                    break;
                }
            }

            
        }
    }
    bool checkNormal(List<Texture2D> textures, int textureCount ,ref string errorTex)
    {
        // 如果图片尺寸不一致，则提示错误
        if (textureCount > 0)
        {
            for (int i = 1; i < textureCount; i++)
            {
                if (null == textures[i])
                {
                    errorTex += "存在空法线";
                    return false;
                }

                if (i > 0 && (textures[i].width != textures[0].width || textures[i].height != textures[0].height))
                {
                    errorTex += "第" + i + "大小不一致";
                    return false;
                }
                if (!IsNormalMap(textures[i]))
                {
                    errorTex += "第" +i+ "张法线不是法线";
                }
                 
            } 
        }
        return true;
    }
    public static bool IsNormalMap(Texture2D texture)
    {
        // 获取纹理的导入设置
        TextureImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;

        if (importer != null)
        {
            // 检查该纹理是否标记为法线贴图
            return importer.textureType == TextureImporterType.NormalMap;
        }

        // 如果无法获取纹理的导入器，返回false
        return false;
    }
    public override void OnInspectorGUI()
    {
        LchTextureArraySettings settings = (LchTextureArraySettings)target;

        EditorGUI.BeginChangeCheck();
        // 拖拽图片
        settings.textureCount = EditorGUILayout.IntField("Texture Count", settings.textureCount  );
        if (settings.textureCount < 1)
            settings.textureCount = 1;
        int textureCount = settings.textureCount;
        settings.textureType = (Tex2dAryType)EditorGUILayout.EnumPopup("Texture Type", settings.textureType);

       
        extendArray(settings.textures, textureCount);

        
        extendArray(settings.normals, textureCount);

        
        extendArray(settings.channels, textureCount);
        

        switch (settings.textureType)
        {
            case Tex2dAryType.Simple:
                {
                    // 用户拖入纹理
                    for (int i = 0; i < textureCount; i++)
                    {
                        GUILayout.Label("第" +i+"层") ;
                        EditorGUILayout.BeginHorizontal();
                        settings.textures[i] = (Texture2D)EditorGUILayout.ObjectField($"图层：", settings.textures[i], typeof(Texture2D), false);
                        settings.normals[i] = (Texture2D)EditorGUILayout.ObjectField($"法线：", settings.normals[i], typeof(Texture2D), false);
                        EditorGUILayout.EndHorizontal();
                    }
                    

                    var normals = settings.normals;
                    var textures = settings.textures;
                    var channels = settings.channels;
                    string errorString="";
                    
                    checkSameSize(textures, textureCount, ref errorString);
                    checkNormal(normals, textureCount, ref errorString);
                    //checkSameSize(settings.channels, textureCount, ref errorString);
                    if (EditorGUI.EndChangeCheck())
                    {
                        EditorUtility.SetDirty(settings);
                        // 提交到磁盘
                        AssetDatabase.SaveAssets();
                    }
                    bool hasError = errorString.Length>0;
                    if (hasError)
                    {
                        EditorGUILayout.HelpBox(errorString, MessageType.Error);
                    }
                    EditorGUI.BeginDisabledGroup(hasError);
                    // 点击创建按钮，生成 Texture2DArray
                    if (GUILayout.Button("Create Texture2D Array"))
                    {
                        string path = AssetDatabase.GetAssetPath(settings);
                        string pathWithoutExtension = System.IO.Path.ChangeExtension(path, null);
                        createTexture(textures, textureCount, pathWithoutExtension+"_DS",false);
                        createTexture(normals, textureCount, pathWithoutExtension + "_NS",true);
                    }
                    EditorGUI.EndDisabledGroup();
                }
                break;
            case Tex2dAryType.PBR:
                {

                    for (int i = 0; i < textureCount; i++)
                    {
                        GUILayout.Label("第" + i + "层");
                        //EditorGUILayout.BeginHorizontal();
                        settings.textures[i] = (Texture2D)EditorGUILayout.ObjectField($"图层：", settings.textures[i], typeof(Texture2D), false);
                        settings.normals[i] = (Texture2D)EditorGUILayout.ObjectField($"法线：", settings.normals[i], typeof(Texture2D), false);
                        settings.channels[i] = (Texture2D)EditorGUILayout.ObjectField($"通道：", settings.channels[i], typeof(Texture2D), false);
                        //EditorGUILayout.EndHorizontal();
                    }

                    var normals = settings.normals;
                    var textures = settings.textures;
                    var channels = settings.channels;
                    string errorString = "";

                    checkSameSize(textures, textureCount, ref errorString);
                    checkNormal(normals, textureCount, ref errorString);
                    checkSameSize(channels, textureCount, ref errorString);
                    //checkSameSize(settings.channels, textureCount, ref errorString);
                    if (EditorGUI.EndChangeCheck())
                    {
                        EditorUtility.SetDirty(settings);
                        // 提交到磁盘
                        AssetDatabase.SaveAssets();
                    }
                    bool hasError = errorString.Length > 0;
                    if (hasError)
                    {
                        EditorGUILayout.HelpBox(errorString, MessageType.Error);
                    }
                    EditorGUI.BeginDisabledGroup(hasError);
                    // 点击创建按钮，生成 Texture2DArray
                    if (GUILayout.Button("Create Texture2D Array"))
                    {
                        string path = AssetDatabase.GetAssetPath(settings);
                        string pathWithoutExtension = System.IO.Path.ChangeExtension(path, null);
                        createTexture(textures, textureCount, pathWithoutExtension + "_DS", false);
                        createTexturePBR(normals, channels, textureCount, pathWithoutExtension + "_MS" );
                        //createTexture(normals, textureCount, pathWithoutExtension + "_NS", true);
                    }
                    EditorGUI.EndDisabledGroup();
                }
                break;
        }
        
       

        // 确保自定义 Inspector 窗口正确显示
        serializedObject.ApplyModifiedProperties();
    }
}